﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using AionCxxLibrary.Utilities;
using System.Xml;
using System.Reflection;
using WorldServer.Models;
using WorldServer.Data.Templates;

namespace WorldServer.Data
{
    /// <summary>
    /// This class holds all static data for the AION emulator.
    /// </summary>
    public class Datastore
    {
        public static Dictionary<int, ItemTemplate> ItemsById = new Dictionary<int, ItemTemplate>();
        public static Dictionary<string, ItemTemplate> ItemsByName = new Dictionary<string, ItemTemplate>();

        public static Dictionary<int, NPCTemplate> NpcsById = new Dictionary<int, NPCTemplate>();
        public static Dictionary<string, NPCTemplate> NpcsByName = new Dictionary<string, NPCTemplate>();

        public static Dictionary<string, SkillLearnTemplate> SkillLearns = new Dictionary<string, SkillLearnTemplate>();

        public static Dictionary<int, SkillTemplate> SkillsById = new Dictionary<int, SkillTemplate>();
        public static Dictionary<string, SkillTemplate> SkillsByName = new Dictionary<string, SkillTemplate>();

        public static Dictionary<int, ClientStringTemplate> StringsById = new Dictionary<int,ClientStringTemplate>();
        public static Dictionary<string, ClientStringTemplate> StringsByName = new Dictionary<string,ClientStringTemplate>();

        public static CharacterInitialData CharactersInitialData;

        public static void Initialize()
        {
            Log.Info("===== Loading Data Store ... =====");
            long start = Utility.DateTimeToTimestamp(DateTime.Now);

            // 1. Client Strings
            foreach (string file in Directory.GetFiles("Data\\Store\\Strings\\", "*.xml", SearchOption.AllDirectories))
            {
                DeserializeAIONXML(file.Replace("Data\\Store\\", ""), typeof(ClientStrings));
            }

            // 2. Client Data
            // 2.1 - Critical Base Data
            DeserializeAIONXML("client_skills.xml", typeof(ClientSkills));
            DeserializeAIONXML("client_items.xml", typeof(ClientItems));
            DeserializeAIONXML("client_npcs.xml", typeof(ClientNpcs));

            // 2.2 - Secondary client data
            DeserializeAIONXML("client_skill_learns.xml", typeof(ClientSkillLearns));

            // 3. Custom Data
            CharactersInitialData = DeserializeCustomXML<CharacterInitialData>("character_initial_data.xml");

            long time = Utility.DateTimeToTimestamp(DateTime.Now) - start;
            Log.Info("===== Loaded Data Store in " + time + " seconds. =====\n");
        }

        static void DeserializeAIONXML(string filename, Type destinationType)
        {
            XmlSerializer ser = new XmlSerializer(destinationType);
            IAionClientFile file = (IAionClientFile)ser.Deserialize(new StreamReader("Data\\Store\\" + filename));
            int loaded = file.GetSize();
            file.PostDeserialize();
            Log.Info("-> Loaded " + loaded + " " + destinationType.Name);
        }

        static T DeserializeCustomXML<T>(string filename)
        {
            XmlSerializer ser = new XmlSerializer(typeof(T));
            return (T)ser.Deserialize(new StreamReader("Data\\Store\\" + filename));
        }

    }

    interface IAionClientFile
    {
        void PostDeserialize();
        int GetSize();
    }
    
    public abstract class IPostDeserializeAwareTemplate
    {
        protected string Normalize(string str)
        {
            if (str == null)
                return null;
            return str.ToLower().Trim().Replace("\0", "");
        }

        public virtual void PostDeserialize()
        {
            //Normalize();
            if (GetRejectedElements() == null || GetOtherElements() == null)
                return;
            foreach (string rej in GetRejectedElements())
            {
                XmlElement elem = GetOtherElements().Find(el => el.Name == rej);
                if (elem != null) GetOtherElements().Remove(elem);
            }
        }
        protected abstract string[] GetRejectedElements();
        protected abstract List<XmlElement> GetOtherElements();
    }

    [XmlRoot(ElementName = "client_items")]
    public class ClientItems : IAionClientFile
    {
        [XmlElement(ElementName = "client_item")]
        public List<ItemTemplate> Templates;

        public int GetSize()
        {
            return Templates.Count;
        }

        public void PostDeserialize()
        {
            foreach (ItemTemplate template in Templates)
            {
                template.PostDeserialize();
                Datastore.ItemsById.Add(template.ID, template);
                Datastore.ItemsByName.Add(template.Name, template);
            }
            Templates.Clear();
        }
    }

    [XmlRoot("skill_base_clients")]
    public class ClientSkills : IAionClientFile
    {
        [XmlElement(ElementName = "skill_base_client")]
        public List<SkillTemplate> Templates;

        public int GetSize()
        {
            return Templates.Count;
        }

        public void PostDeserialize()
        {
            foreach (SkillTemplate template in Templates)
            {
                template.PostDeserialize();
                Datastore.SkillsById.Add(template.ID, template);
                Datastore.SkillsByName.Add(template.Name, template);
            }
            Templates.Clear();
        }
    }

    [XmlRoot("client_skill_learns")]
    public class ClientSkillLearns : IAionClientFile
    {
        [XmlElement(ElementName = "client_skill_learn")]
        public List<SkillLearnTemplate> Templates;

        public int GetSize()
        {
            return Templates.Count;
        }

        public void PostDeserialize()
        {
            foreach (SkillLearnTemplate template in Templates)
            {
                template.PostDeserialize();
                Datastore.SkillLearns.Add(template.Name, template);
            }
            Templates.Clear();
        }
    }

    [XmlRoot("strings")]
    public class ClientStrings : IAionClientFile
    {
        [XmlElement("string")]
        public List<ClientStringTemplate> Templates;

        public void PostDeserialize()
        {
            foreach (ClientStringTemplate template in Templates)
            {
                template.PostDeserialize();
                Datastore.StringsById.Add(template.ID, template);
                Datastore.StringsByName.Add(template.Name, template);
            }
            Templates.Clear();
        }

        public int GetSize()
        {
            return Templates.Count;
        }

    }

    [XmlRoot("npc_clients")]
    public class ClientNpcs : IAionClientFile
    {
        [XmlElement("npc_client")]
        public List<NPCTemplate> Templates;

        public void PostDeserialize()
        {
            foreach (NPCTemplate template in Templates)
            {
                template.PostDeserialize();
                Datastore.NpcsById.Add(template.ID, template);
                Datastore.NpcsByName.Add(template.Name, template);
            }
            Templates.Clear();
        }

        public int GetSize()
        {
            return Templates.Count;
        }

    }

}
